<template>
    <div>
        <el-drawer
            :title="JSON.stringify(drawer.row)!='{}'?'编辑顾问':'新增顾问'"
            :visible.sync="drawer.visible"
            direction="rtl"
            size="60%"
            custom-class="demo-drawer"
            ref="drawer"
            :before-close="handleClose"
        >
            <div class="demo-drawer__content" ref="content">
                <el-form :model="form" ref="form" id="form" label-position="right" label-width="120px" size="small" :rules="rules">
                    <el-form-item label="视频咨询头像" class="item_upload" prop="file_list">
                        <el-upload
                            class="upload-box"
                            action="#"
                            list-type="picture-card"
                            :file-list="form.file_list"
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                            :auto-upload="false"
                            :limit="imageLimit"
                            :accept="imageAccept.join(',')"
                            :multiple="false"
                            :on-change="handleChange"
                            :class="{'upload-box': true, 'hideUpload': uploadDisplay}"
                            ref="upload"
                        >
                            <i class="el-icon-plus"></i>
                            <div class="el-upload__tip" slot="tip">
                                分辨率：300*300 (px), 系统支持的图片格式为：gif、jpg、jpeg、png, 大小限制为2M内
                            </div>
                        </el-upload>
                        <el-dialog :visible.sync="dialog.visible" append-to-body>
                            <img width="100%" :src="dialog.imageUrl" alt="">
                        </el-dialog>
                    </el-form-item>
                    <el-form-item label="视频咨询名称" prop="group_name">
                        <el-input type="text" class="input" maxlength="40" autocomplete="off" v-model="form.group_name"></el-input>
                    </el-form-item>
                    <el-form-item label="视频咨询称号" prop="team_name">
                        <el-input type="text" class="input" maxlength="40" autocomplete="off" v-model="form.team_name"></el-input>
                    </el-form-item>
                    <el-form-item label="顾问手机号" class="mobile" prop="consultant_data">
                        <el-form-item v-for="(value, key) in form.consultant_data" :key="key" label="" :prop="`consultant_data.${key}`" :rules="rules.mobile">
                            <el-row>
                                <el-input type="text" class="input" maxlength="11" placeholder="输入手机号" autocomplete="off" v-model="form.consultant_data[key]"></el-input>
                                <el-button type="danger" @click="delMobile(key)" title="删除手机号">删除</el-button>
                            </el-row>
                        </el-form-item>
                        <el-row>
                            <el-button type="primary" @click="addMobile">新增手机号</el-button>
                            <div class="desc">(手机号需先在车家佳进行登录注册)</div>
                        </el-row>
                    </el-form-item>
                    <el-form-item label="排序字段" prop="sort"> 
                        <el-input type="text" class="form-sort" autocomplete="off" v-model.number="form.sort"></el-input>
                    </el-form-item>
                    <el-form-item label="声讯电话通知">
                        <el-checkbox v-model="form.can_dial">开通</el-checkbox>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="closeDrawer">取 消</el-button>
                        <el-button
                            type="primary"
                            @click="submitForm('form')"
                            :loading="loading"
                            >{{ loading ? "提交中 ..." : "确 定" }}</el-button
                        >
                    </el-form-item>
                </el-form>
                <!--div class="demo-drawer__footer">
                    <el-button size="small" @click="closeDrawer">取 消</el-button>
                    <el-button size="small"
                        type="primary"
                        @click="submitForm"
                        :loading="loading"
                    >
                        {{ loading ? "提交中 ..." : "确 定" }}
                    </el-button>
                </div-->
            </div>
        </el-drawer>
    </div>
</template>
<script>
import {adviserSave} from './urlApi'
export default {
    props: ['drawer'],     // 接收父组件传值
    data() {
        let checkPhone = (rule, value, callback) => {
            if (!value || !/^1\d{10}$/.test(value)) {
                //callback(new Error('请输入11位有效手机号号码'))
                callback(new Error()) // 这里不输入提示，则按rules 里设置的提示显示
            } else {
                callback()
            }
        };
        return {
            imageAccept: ['image/jpeg', 'image/jpg', 'image/gif', 'image/png'],
            imageSzie: 2,
            imageLimit: 1,
            uploadDisplay: false,
            dialog: {visible: false, imageUrl: null},
            formDefault: {
                group_avatar: "",
                group_name: "",
                sort: "",
                team_name: "",
                consultant_data: null,
                file_list: [],
                can_dial: 0,
            },
            form: {},
            loading: false,
            rules: {
                file_list: [
                    { required: true, message: '请上传顾问头像', trigger: 'change' }
                ],
                group_name: [
                    { required: true, message: '请输入视频咨询名称', trigger: 'blur' }
                ],
                team_name: [
                    { required: true, message: '请输入视频咨询称号', trigger: 'blur' }
                ],
                consultant_data: [
                    { required: true, message: '请添加顾问手机号', trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请填写顾问手机号', trigger: 'blur' },
                    { type: 'number', validator: checkPhone, message: '请输入11位有效手机号号码', trigger: ['blur', 'change'] }
                ],
                sort: [
                    { required: true, message: '请输入排序字段', trigger: 'blur' }
                ]
            },
        }
    },
    created() {},
    methods: {
        handlePreview(file) {
            this.dialog = {visible: true, imageUrl: file.url};
        },
        async handleRemove(file, fileList) {
            if(fileList.length < 1) {
                this.rules.file_list = [{ required: true, message: '请上传顾问头像', trigger: 'change'}];
                this.form.group_avatar = ""; // 删除头像，则清空头像部分路径后端检测到group_avatar为空则表示删除头像
            }
            this.form.file_list = fileList
            this.uploadDisplay = fileList.length >= this.imageLimit;
        },
        handleChange(file, fileList) {
            const isValid = this.imageAccept.indexOf(file.raw.type);
            const isLt2M = file.size / 1024 / 1024 < 2;
            this.uploadDisplay = fileList.length >= this.imageLimit
            if (isValid < 0) {
                this.$message.error('上传头像图片只能是 '+this.imageAccept.join(", ").replace(/image\//g, "")+' 格式!');
                return false;
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
                return false;
            }
            this.form.file_list = fileList;
            this.form.avatar_file = fileList[0].raw;
            /*
            // 删除rules中的file_list属性, 此方法会造成上传图片即对所有进行验证，因为rules 重新赋值的缘故
            let {file_list, ...data} = this.rules; 
            this.rules = data;
            */
            delete this.rules.file_list; // 删除rules中的file_list属性
            this.$refs.form.clearValidate("file_list"); // 移除file_list校验结果
        },
        handleClose(done) {
            this.$confirm('确定要关闭表单吗？')
            .then(() => {
                this.closeDrawer(function() {
                    done();
                });
            })
            .catch(() => { });
        },
        delMobile(index) {
            this.$confirm('确定要删除该手机号吗？')
            .then(() => {
                this.form.consultant_data.splice(index, 1);
            })
            .catch(() => { });
        },
        addMobile() {
            if(this.form.consultant_data) {
                this.form.consultant_data.push(null);
            } else {
                this.form.consultant_data = [null];
            }

            // 移除consultant_data校验结果
            this.$refs.form.clearValidate("consultant_data"); 
        }, 
        closeDrawer(cb = null) {
            if(this.loading) return; // 正在提交数据则禁止关闭窗口
            this.loading = false;
            this.$refs.form.resetFields();
            this.$refs.upload.clearFiles();
            this.form.file_list = [];
            this.$emit("closeDrawer");
            /*
            if(typeof cb == "function") {
                cb()
            } else {
                this.drawer.visible = false;
            }*/
        },
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    this.loading = true;
                    let formData = new FormData();
                    let unArr = ["file_list", "group_avatar_full", "create_time", "can_dial_text", "index", "isChange"]; //不需要传递的字段
                    for(let [key, value] of Object.entries(this.form)) {
                        if(unArr.indexOf(key) >= 0) continue;
                        if(key == "can_dial") value = Number(value);
                        // console.log(key, value);
                        formData.append(key, value);
                    }
                    adviserSave.save(formData).then(res => {
                        this.loading = false;
                        // console.log(res) 
                        if(res.code == 1) {
                            this.closeDrawer();
                            this.$message.success(res.msg)
                            this.$emit("getData");
                        } else {
                            this.$message.error(res.msg)
                        }
                    }).catch(res => {
                        console.log(res)
                    })
                } else {
                    this.$message.error("请检测必填、必选项！")
                    return false;
                }
            });
        },
	},
	watch: {
        "drawer.row": {
            immediate: true,
            handler: function(val, oldVal) {
                if(!val) return;
                if(val.group_id) {
                    if(val.group_avatar_full && val.group_avatar) {
                        val.file_list = [{name: val.group_avatar, url: val.group_avatar_full}]
                    } else {
                        val.file_list = [];
                    }
                } else {
                    val = JSON.parse(JSON.stringify(this.formDefault));
                }
                val.can_dial = Boolean(parseInt(val.can_dial));
                this.uploadDisplay = val.file_list.length >= this.imageLimit;
                this.rules.file_list = [{ required: true, message: '请上传顾问头像', trigger: 'change'}];
                this.form = val;
            }
        }
    }
}
</script>
<style lang="scss" scoped>
/deep/.el-drawer.rtl {
    overflow-y: auto;
    .demo-drawer__footer {
        position: absolute;
        bottom: 10px;
        left: 20px;
    }
}

.el-form{ 
    padding: 10px 40px;
    max-width: 800px;
    /deep/.item_upload {
      .el-form-item__label {
        line-height: 148px;
        display: block;
      }
    }
    .upload-box, .el-upload__tip{
      display: flex;
      justify-content: flex-start;
    }
    /deep/.upload-box {
      align-items: top;
      padding-bottom: 0;
      .el-upload-list{
          height:154px;
      }
      &.hideUpload .el-upload{
        display: none;
      }
      .el-upload {
        flex-shrink: 0;
        line-height: 152px;
      }
      .el-upload__tip {
        align-items: center;
        padding-left:16px;
        margin: 0px;
        line-height: 180%;
        height: 150px;
      }
    }
    /deep/.mobile .el-row{
        display:flex;
        align-items: center;
        justify-content: flex-start;
        margin-bottom: 10px;
        .el-input{
            margin: 0 10px 0px 0;
        }
        &:last-child{margin-bottom:0}
        .desc {
            margin-left:16px;
            color:#999;
        }
    }
    /deep/.form-sort input{width:100px;}
    /deep/.el-checkbox__inner{zoom: 130%;}
    /deep/.el-form-item__error{
        position: relative;
        margin: 6px 0 -4px;
    }
}
</style>
